import React, { useEffect, useState } from 'react'
import '../../style/songListlist.css'
import { useGlobalContext } from '../GlobalContext'

const songListlist = ({ onviblechange, songsend }) => {
  const { userId, setUserId, persongListrefresh, setPerSonglistRefresh } = useGlobalContext();
  const [PersonalSonglist, setPersonalSonglist] = useState([])
  useEffect(() => {
    fetch(`http://localhost:8088/songlist/all/${userId}`)
      .then((response) => response.json())
      .then((data) => {
        setPersonalSonglist(data.data)
      })
      .catch((error) => {
        console.error('Error fetching song data:', error);
      })
  }, [persongListrefresh, userId])
  // const [songlistId, setSonglistId] = useState('');

  const handlesonglistId = async (id) => {
    const songPost = {
      musicId: songsend.musicId,
      musicName: songsend.musicName,
      artName: songsend.artName,
      album: songsend.album,
      coverUrl: songsend.coverUrl,
      playUrl: songsend.playUrl,
      lyricUrl: `http://localhost:3000/lyric?id=${songsend.musicId}`,
      dt: songsend.dt,
      liked: songsend.liked,
      userId,
      songListId: id,
    };
    try {
      // 添加到歌单
      const response = await fetch("http://localhost:8088/songs", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(songPost),
      });

      if (!response.ok) {
        throw new Error("Failed to addsong to songlist status");
      }
      alert("添加成功")
      onviblechange(false)
    } catch (error) {
      console.error("Error handling addsong to songlist request: ", error);
    }
  }
  return (
    <div className='site3'>
      <div className="addtitle">
        添加到歌单
        <button onClick={() => onviblechange(false)}>取消</button>
      </div>
      <ul className='songlismainmain'>
        {PersonalSonglist.map((item) => (
          <li className='sonlisli' onDoubleClick={() => handlesonglistId(item.songlistId)}>
            <img className='songlistliimg' src={item.coverUrl} alt="" />
            <div className="songlistliName">{item.songListName}</div>
          </li>
        ))}
      </ul>
    </div>
  )
}

export default songListlist